#include "volumetool.h"
#include "ui_volumetool.h"

#include <QGraphicsDropShadowEffect>
#include <QPainter>
VolumeTool::VolumeTool(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::VolumeTool),
    isMuted(false),
    volumeRatio(20)
{
    ui->setupUi(this);

    setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);

    setAttribute(Qt::WA_TranslucentBackground);

    QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0, 0);
    shadowEffect->setColor("#646464");
    shadowEffect->setBlurRadius(10);
    setGraphicsEffect(shadowEffect);

    ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));

    ui->outLine->setGeometry(ui->outLine->x(), 180-36+25, ui->outLine->width(), 36);
    ui->sliderBtn->move(ui->sliderBtn->x(), ui->outLine->y() - ui->silenceBtn->height()/2 + 10);
    ui->volumeRatio->setText("20%");

    connect(ui ->silenceBtn, &QPushButton::clicked, this, &VolumeTool::onSilenceBtnClicked);

    ui->sliderBox->installEventFilter(this);
}

VolumeTool::~VolumeTool()
{
    delete ui;
}

void VolumeTool::paintEvent(QPaintEvent *event)
{
    // 绘制volumetool界面下的三角
    QPainter painter(this);

    // 设置画笔
    painter.setPen(Qt::NoPen);
    // 设置画刷
    painter.setBrush(QBrush(Qt::white));
    // 绘制三角形
    QPolygon polygon;
    QPoint a(10, 300);
    QPoint b(10+80, 300);
    QPoint c(10+40, 300+20);

    polygon.append(a);
    polygon.append(b);
    polygon.append(c);

    painter.drawPolygon(polygon);
}

bool VolumeTool::eventFilter(QObject *watched, QEvent *event)
{
    if(ui->sliderBox == watched)
    {
        // 发生在sliderBox上
        if(event->type() == QEvent::MouseButtonPress)
        {
            // 鼠标按下
            calcVolume();
        }
        else if(event->type() == QEvent::MouseButtonRelease)
        {
            // 鼠标释放
            emit setMusicVolume(volumeRatio);
        }
        else if(event->type() == QEvent::MouseMove)
        {
            // 鼠标移动
            calcVolume();
            emit setMusicVolume(volumeRatio);
        }
        return true;
    }
    return QObject::eventFilter(watched, event);
}

void VolumeTool::calcVolume()
{
    int height = ui->sliderBox->mapFromGlobal(QCursor().pos()).y();

    height = height < 25 ? 25 : height;
    height = height > 205 ? 205 : height;

    ui->outLine->setGeometry(ui->outLine->x(), height, ui->outLine->width(), 205-height);

    ui->sliderBtn->move(ui->sliderBtn->x(), ui->outLine->y() - ui->silenceBtn->height()/2 + 10);

    volumeRatio = (int)(ui->outLine->height()/(float)180*100);

    ui->volumeRatio->setText(QString::number(volumeRatio)+"%");
}

void VolumeTool::onSilenceBtnClicked()
{
    isMuted = !isMuted;
    if(isMuted)
    {
        ui->silenceBtn->setIcon(QIcon(":/images/silent.png"));
    }
    else
    {
        ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));
    }

    emit setMusicMuted(isMuted);
}
